<?php

namespace App\Extensions;

use Encore\Admin\Form\Field;
use Encore\Admin\Widgets\Chart\Chart;
use Encore\Admin\Widgets\Widget;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Support\Arr;

class LineChart extends Field
{
    protected $view = 'Admin.Tool.LineChart';
    protected static $js = [
        '/plugins/charts/echarts.min.js'
    ];

    protected $data = [];
    protected $xValue = [];

    public function __construct($xValue = [], $data = [])
    {
        parent::__construct([]);
        $this->data = $data;
        $this->xValue = $xValue;
    }

    public function render()
    {
        $attributes = $this->data;
        $xValue = json_encode($this->xValue);
        $keys = array_keys($attributes);
        $lines = json_encode($keys);
        $this->script = <<<EOT
        $(function(){
            var myChart = echarts.init(document.getElementById('main'));
            var option = {
                tooltip : {
                    trigger: 'axis'
                },
                legend: {
                    data:{$lines}
                },
                toolbox: {
                    show : true,
                    feature : {
                        mark : {show: true},
                        dataView : {show: true, readOnly: false},
                        magicType : {show: true, type: ['line']},
                        restore : {show: true},
                        saveAsImage : {show: true}
                    }
                },
                calculable : true,
                xAxis : [
                    {
                        type : 'category',
                        data : {$xValue},
                    }
                ],
                yAxis : [
                    {
                        type : 'value'
                    }
                ],
                series : [
EOT;
        foreach ($attributes as $key => $val) {
            $val = json_encode($val);
            $this->script .= <<<EOT
                    {
                        name:'{$key}',
                        type:'line',
                        data:{$val},
                        markPoint : {
                            data : [
                                {type : 'max', name: '最大值'},
                                {type : 'min', name: '最小值'}
                            ]
                        },
                        markLine : {
                            data : [
                                {type : 'average', name: '平均值'}
                            ]
                        }
                    },
EOT;
        }
        $this->script .= <<<EOT
                ]
            };
            myChart.setOption(option);
        });
EOT;
        return parent::render();
    }
}
